/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * desencripta.java
 *
 * Created on Oct 10, 2012, 12:11:51 AM
 */
package desencriptador;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import desensamble.*;
import javax.swing.JOptionPane;


/**
 *
 * @author DAVID GATJENS
 */
public class desencripta extends javax.swing.JFrame {
    
    String ruta_archivo = "";
    String key;
    String op;
    String op2;
    String cant;
    String hex;
    String encriptado;
    int diccionario;
    int tamanio;
    int posicion [][];
    desensamble.Diccionarios dic = new desensamble.Diccionarios();
   

    /** Creates new form desencripta */
    public desencripta() {
        initComponents();
        
        dic.llenar_primero();
        dic.llenar_segundo();
        dic.llenar_tercero();
        dic.llenar_cuarto();

        dic.llenar_numero();
        dic.llenar_let();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblseleccion = new javax.swing.JLabel();
        btnExaminar = new javax.swing.JButton();
        txtRuta = new javax.swing.JTextField();
        btnCargar = new javax.swing.JButton();
        lblencriptado = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txaEncriptado = new javax.swing.JTextArea();
        lblclabe = new javax.swing.JLabel();
        txtKey = new javax.swing.JTextField();
        btnDesencriptar = new javax.swing.JButton();
        lblDesencriptado = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaDesencriptado = new javax.swing.JTextArea();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Desencriptador"); // NOI18N

        lblseleccion.setFont(new java.awt.Font("Vani", 1, 12));
        lblseleccion.setText("Seleccione el archivo a desencritar:");

        btnExaminar.setText("Examinar");
        btnExaminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExaminarActionPerformed(evt);
            }
        });

        txtRuta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRutaActionPerformed(evt);
            }
        });

        btnCargar.setText("Cargar");
        btnCargar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCargarActionPerformed(evt);
            }
        });

        lblencriptado.setFont(new java.awt.Font("Vani", 1, 12));
        lblencriptado.setText("Texto Encriptdo");

        txaEncriptado.setColumns(20);
        txaEncriptado.setEditable(false);
        txaEncriptado.setRows(5);
        jScrollPane1.setViewportView(txaEncriptado);
        txaEncriptado.setLineWrap(true);

        lblclabe.setFont(new java.awt.Font("Vani", 1, 12));
        lblclabe.setText("Clave de Desencriptación:");

        btnDesencriptar.setText("Desencriptar");
        btnDesencriptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesencriptarActionPerformed(evt);
            }
        });

        lblDesencriptado.setFont(new java.awt.Font("Vani", 1, 12));
        lblDesencriptado.setText("Texto Desencriptado");

        txaDesencriptado.setColumns(20);
        txaDesencriptado.setEditable(false);
        txaDesencriptado.setRows(5);
        jScrollPane2.setViewportView(txaDesencriptado);
        txaDesencriptado.setLineWrap(true);

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblseleccion, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
                                .addGap(331, 331, 331))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                                    .addComponent(txtRuta, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(89, 89, 89)
                                        .addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(btnExaminar, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
                                        .addGap(18, 18, 18)
                                        .addComponent(btnCargar, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(txtKey, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                                            .addComponent(lblclabe, javax.swing.GroupLayout.Alignment.LEADING))
                                        .addGap(1, 1, 1))
                                    .addComponent(btnDesencriptar))))
                        .addGap(26, 26, 26))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblencriptado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(476, 476, 476))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblDesencriptado)
                        .addContainerGap(448, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addComponent(lblseleccion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExaminar)
                    .addComponent(btnCargar)
                    .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblencriptado)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblclabe)
                        .addGap(18, 18, 18)
                        .addComponent(txtKey, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addComponent(btnDesencriptar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblDesencriptado)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2))
                    .addComponent(btnCancelar))
                .addGap(43, 43, 43))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtRutaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRutaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRutaActionPerformed

    private void btnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExaminarActionPerformed
//       permite buscar un archivo txt para cargar en la interface
        JFileChooser archivo = new JFileChooser();
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivos TXT", "txt");
        File ruta;
        
        
        archivo.setFileFilter(filtro);
        
        int opcion = archivo.showOpenDialog(null);
        
        if (opcion == JFileChooser.APPROVE_OPTION){
            
           ruta = archivo.getSelectedFile();
           
           ruta_archivo = ruta.getPath();
           txtRuta.setText(ruta_archivo);
           }
    }//GEN-LAST:event_btnExaminarActionPerformed

    private void btnCargarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCargarActionPerformed
        // Carga la informacion del archivo txt en la interface del sistema
        File ruta = new File(ruta_archivo);
        BufferedReader textoEncriptado;
        try {
            textoEncriptado = new BufferedReader( new FileReader(ruta));
            String textoLeido = "";
            while(textoEncriptado.ready()){
                textoLeido += textoEncriptado.readLine();
            }
            txaEncriptado.setText(textoLeido);
            
        } catch (IOException e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
            
        
        
    }//GEN-LAST:event_btnCargarActionPerformed

    private void btnDesencriptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDesencriptarActionPerformed
        // Hace las llamadas a los diferentes diccionarios y hace los procesos y calculos intersos a la encriptacion
        String verificacion;
        String primeraDesencriptacion ="";
        String segundaDesencriptacion ="";
        String terceraDesencriptacion ="";
        int calculo = 0;
       
        
        key = txtKey.getText();
        try {
            if(key.length() == 9){
                op = key.substring(0,2);
                cant = key.substring(2,4);
                op2 = key.substring(4,6);
                hex = key.substring(6,7);
                diccionario = Integer.parseInt(key.substring(7,9));
            }else if(key.length()< 9){
            
                JOptionPane.showMessageDialog(null,"La clave no cumple con las espesificaciones mínimas de longitud");            
            
            }
//            
        } catch (Exception e) {
            
          JOptionPane.showMessageDialog(null, "Error en el proceso");
        }
        
        
        
       switch (diccionario){
           
           case 1:
                    encriptado = txaEncriptado.getText();
                    for(int contador = 0; contador <= encriptado.length()-1; contador++){
                        verificacion = encriptado.substring(contador, contador+1);

                        for(int arreglo = 0; arreglo <=95; arreglo++){

                            if(dic.primero[0][arreglo].equals(verificacion) == true ){
                                primeraDesencriptacion = dic.primero[1][arreglo];
                                
                              for(int recorre =0; recorre<=95;recorre++){
                              if(dic.numero[0][recorre].equals(primeraDesencriptacion)==true){
                                  segundaDesencriptacion = dic.numero[1][recorre];
                                  if(op2.equals("DV")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)-Integer.parseInt(hex);
                                        }
                                        else if(op2.equals("ML")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)+Integer.parseInt(hex);
                                        }
                                  if(op.equals("SR")==true){
                                            calculo = calculo - Integer.parseInt(cant);
                                        }
                                        else if(op.equals("RS")==true){
                                            calculo = calculo + Integer.parseInt(cant);
                                        }
                                  for(int fin =0;fin <=288;fin++){
                                      if(dic.let[0][fin].equals(String.valueOf(calculo))==true){
                                      
                                        terceraDesencriptacion += dic.let[1][fin];
                                        fin = 289;
                                  }
                                      
                                  }
                                  
                              }
                               
                            }
                         
                          }
                            
                        }
                        
                    }
                   txaDesencriptado.setText(terceraDesencriptacion); 
               break;
           case 2:
                    encriptado = txaEncriptado.getText();
                    for(int contador = 0; contador <= encriptado.length()-1; contador++){
                        verificacion = encriptado.substring(contador, contador+1);

                        for(int arreglo = 0; arreglo <=95; arreglo++){

                            if(dic.segundo[0][arreglo].equals(verificacion) == true ){
                                primeraDesencriptacion = dic.segundo[1][arreglo];
                                
                              for(int recorre =0; recorre<=95;recorre++){
                              if(dic.numero[0][recorre].equals(primeraDesencriptacion)==true){
                                  segundaDesencriptacion = dic.numero[1][recorre];
                                  if(op2.equals("DV")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)-Integer.parseInt(hex);
                                        }
                                        else if(op2.equals("ML")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)+Integer.parseInt(hex);
                                        }
                                  if(op.equals("SR")==true){
                                            calculo = calculo - Integer.parseInt(cant);
                                        }
                                        else if(op.equals("RS")==true){
                                            calculo = calculo + Integer.parseInt(cant);
                                        }
                                  for(int fin =0;fin <= 288;fin++){
                                      if(dic.let[0][fin].equals(String.valueOf(calculo))==true){
                                      
                                        terceraDesencriptacion += dic.let[1][fin];
                                        fin = 289;
                                      }
                                      
                                  }
                                  
                              }
                              
                            }
                             
                            }
                            
                        }
                        
                    }
                   txaDesencriptado.setText(terceraDesencriptacion); 

               break;

           case 3:
                    encriptado = txaEncriptado.getText();
                    for(int contador = 0; contador <= encriptado.length()-1; contador++){
                        verificacion = encriptado.substring(contador, contador+1);

                        for(int arreglo = 0; arreglo <=95; arreglo++){

                            if(dic.tercero[0][arreglo].equals(verificacion) == true ){
                                primeraDesencriptacion = dic.tercero[1][arreglo];
                                
                              for(int recorre =0; recorre<=95;recorre++){
                              if(dic.numero[0][recorre].equals(primeraDesencriptacion)==true){
                                  segundaDesencriptacion = dic.numero[1][recorre];
                                  if(op2.equals("DV")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)-Integer.parseInt(hex);
                                        }
                                        else if(op2.equals("ML")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)+Integer.parseInt(hex);
                                        }
                                  if(op.equals("SR")==true){
                                            calculo = calculo - Integer.parseInt(cant);
                                        }
                                        else if(op.equals("RS")==true){
                                            calculo = calculo + Integer.parseInt(cant);
                                        }
                                  for(int fin =0;fin <=288;fin++){
                                      if(dic.let[0][fin].equals(String.valueOf(calculo))==true){
                                      
                                        terceraDesencriptacion += dic.let[1][fin];
                                        fin = 289;
                                  }
                                      
                                  }
                                  
                              }
                               
                            }
                          }
                            
                        }
                        
                    }
                   txaDesencriptado.setText(terceraDesencriptacion); 

               break;

           case 4:
                    encriptado = txaEncriptado.getText();
                    for(int contador = 0; contador <= encriptado.length()-1; contador++){
                        verificacion = encriptado.substring(contador, contador+1);

                        for(int arreglo = 0; arreglo <=95; arreglo++){

                            if(dic.cuarto[0][arreglo].equals(verificacion) == true ){
                                primeraDesencriptacion = dic.cuarto[1][arreglo];
                                
                              for(int recorre =0; recorre<=95;recorre++){
                              if(dic.numero[0][recorre].equals(primeraDesencriptacion)==true){
                                  segundaDesencriptacion = dic.numero[1][recorre];
                                  if(op2.equals("DV")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)-Integer.parseInt(hex);
                                        }
                                        else if(op2.equals("ML")==true){
                                            calculo = Integer.parseInt(segundaDesencriptacion)+Integer.parseInt(hex);
                                        }
                                  if(op.equals("SR")==true){
                                            calculo = calculo - Integer.parseInt(cant);
                                        }
                                        else if(op.equals("RS")==true){
                                            calculo = calculo + Integer.parseInt(cant);
                                        }
                                  for(int fin =0;fin <=288;fin++){
                                      if(dic.let[0][fin].equals(String.valueOf(calculo))==true){
                                      
                                        terceraDesencriptacion += dic.let[1][fin];
                                        fin = 289;
                                  }
                                      
                                  }
                                  
                              }
                              
                            }
                                
                          }
                            
                        }
                        
                    }
                   txaDesencriptado.setText(terceraDesencriptacion); 

               break;

           
       }
        
        
    }//GEN-LAST:event_btnDesencriptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(desencripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(desencripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(desencripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(desencripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new desencripta().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnCargar;
    private javax.swing.JButton btnDesencriptar;
    private javax.swing.JButton btnExaminar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblDesencriptado;
    private javax.swing.JLabel lblclabe;
    private javax.swing.JLabel lblencriptado;
    private javax.swing.JLabel lblseleccion;
    private javax.swing.JTextArea txaDesencriptado;
    private javax.swing.JTextArea txaEncriptado;
    private javax.swing.JTextField txtKey;
    private javax.swing.JTextField txtRuta;
    // End of variables declaration//GEN-END:variables
}
